package com.ruoyi.common.utils;

import java.io.UnsupportedEncodingException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.ruoyi.common.config.Global;
import com.ruoyi.common.json.JSON;
import com.ruoyi.common.json.JSONObject;
import com.ruoyi.common.utils.http.HttpUtils;

/**
 * 获取地址类
 * 
 * @author ruoyi
 */
@Component

public class AddressUtils
{
    private static final Logger log = LoggerFactory.getLogger(AddressUtils.class);

    //public static final String IP_URL = "http://ip.taobao.com/service/getIpInfo.php";
    public static final String IP_URL = "http://gwgp-hye6ycojwut.n.bdcloudapi.com/getIpInfo";
  
    public static String getRealAddressByIP(String ip)
    {
        String address = "XX XX";
        // 内网不查询
        if (IpUtils.internalIp(ip))
        {
            return "内网IP";
        }
        if (Global.isAddressEnabled())
        {
        	String rspStr;
        	if(Global.getAddressIp().trim().contains("taobao")) {
        		rspStr = HttpUtils.sendPost(Global.getAddressIp(), "ip=" + ip);
        	}else {
        		rspStr = HttpUtils.sendGet(Global.getAddressIp(), "ip=" + ip);
        	}
            if (StringUtils.isEmpty(rspStr))
            {
                log.error("获取地理位置异常 {}", ip);
                return address;
            }
            JSONObject obj;
            try
            {
                obj = JSON.unmarshal(rspStr, JSONObject.class);
                JSONObject data = obj.getObj("data");
                if(Global.getAddressIp().trim().contains("taobao")) {
                	String region = data.getStr("region");
                	String city = data.getStr("city");
                	address = region + " " + city;
                }else {
                	String country = data.getStr("country");
                    String prov = data.getStr("prov");
                    String city = data.getStr("city");
                    String isp = data.getStr("isp");
                    address = country + " " + prov + " " + city + " " + isp;
                }
            }
            catch (Exception e)
            {
                log.error("获取地理位置异常 {}", ip);
            }
        }
        return address;
    }
}
